package com.xyq.fs.index;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.Field.Store;

import com.xyq.fs.base.MyDirectoryS;
import com.xyq.fs.constants.FieldConstant;
import com.xyq.fs.constants.IndexStringConstants;
import com.xyq.fs.util.FileCodingUtil2;

/**
 * 索引txt文本
 * 
 * @author xyqq
 *
 */
public class IndexTxtFiles implements IndexFileInf {

	@Override
	public void indexFile(Path path, String bz) {

		String fname = path.getFileName().toString().toUpperCase();
		int n = fname.lastIndexOf(IndexStringConstants.DIAN);
		String suffix = fname.substring(n);
		Document doc = getSimDoc(path, suffix, bz);

		if (path.toFile().length() > 0) {

			try {
				suffix = FileCodingUtil2.getCharsetName(path, 1024);
				try (FileInputStream fis = new FileInputStream(path.toFile());
						Reader reader = new InputStreamReader(fis, suffix)) {
					TextField tx = new TextField(FieldConstant.FILE_CONTENT, reader);
					doc.add(tx);
					if (bz != null) {
						doc.add(new StringField(FieldConstant.FILE_BZ_SORT, bz, Store.YES));
					}
					MyDirectoryS.addDocument(doc);
					tx = null;
					doc.clear();
					doc = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				fname = null;
				suffix = null;
				bz = null;
				path = null;
			}
		}
	}

	public static void main(String[] args) throws IOException {

		Path path = Paths.get("f:\\2.txt");
		String s = FileCodingUtil2.getCharsetName(path, 1024);
		System.out.println(s);

	}
}
